﻿using MM.Contract.Core;
using NHibernate;
using uNhAddIns.Entities;

namespace MM.Persistence.NH.Repositories
{
    public class Repository<T> : IRepository<T>
    {
        private readonly ISessionFactory factory;

        public Repository(ISessionFactory factory)
        {
            this.factory = factory;
        }

        protected ISession Session
        {
            get { return factory.GetCurrentSession(); }
        }

        #region Miembros de IRepository<T>

        public T Get(object id)
        {
            return Session.Get<T>(id); 
        }

        public T Load(object id)
        {
            return Session.Load<T>(id);
        }

        public T MakePersistent(T entity)
        {
            Session.Persist(entity);
            return entity;
        }

        public void Refresh(T entity)
        {
            if ((entity is Entity)
                 && (entity as Entity).Id == 0)
                return;

            var id = Session.GetIdentifier(entity);
            Session.Evict(entity);
            Session.Load(entity, id);
        }

        public void MakeTransient(T entity)
        {
            Session.Delete(entity);
        }

        public void UpdateChange(T entity) {
            Session.SaveOrUpdate(entity);
        }
        #endregion
    }
}
